package old_go_learn

import (
	"fmt"
	"strconv"
	"net/http"
	"os"
)

func main(){
	var start,end int

	fmt.Println("请输入起始页(>=1):")
	fmt.Scan(&start)

	fmt.Println("请输入终止业(>=起始页):")
	fmt.Scan(&end)

	DoWork(start,end)


}

func DoWork(start int,end int){

	page := make(chan int)

	for i:=start;i<=end;i++{
		go SpiderPage(i,page)
	}

	for j := start;j<=end;j++{
		fmt.Printf("第%d个页面爬取完成\n", <-page)
	}
}


func HttpGet(url string) (result string,err error){
	resp,err1 := http.Get(url)
	if err1 != nil{
		err = err1
		return
	}

	defer resp.Body.Close()

	buf := make([]byte,1024*4)

	for{
		n,err := resp.Body.Read(buf)
		if n ==0 {
			fmt.Println("resp.Body.Read err",err)
			break
		}

		result += string(buf[:n])
	}

	return
}


func SpiderPage(i int,page chan <-int){
	url := "https://tieba.baidu.com/f?kw=%E7%BB%9D%E5%9C%B0%E6%B1%82%E7%94%9F&ie=utf-8&pn="+strconv.Itoa((i-1)*50)

	fmt.Println(url)

	res,err := HttpGet(url)
	if err != nil{
		fmt.Println("HttpGet err = ",err)
		return
	}

	fmt.Println(res)
	fileName := strconv.Itoa(i) + ".html"
	f,err1 := os.Create(fileName)
	if err1 != nil{
		fmt.Println("os.Create err =",err1)
		return
	}

	f.WriteString(res)
	f.Close()

	page <- i
}